package com.xyy.saas.payment.payment.core.service;

import com.xyy.saas.payment.callback.core.result.CallbackRunner;
import com.xyy.saas.payment.common.RocketMqTopic;
import com.xyy.saas.payment.dao.model.PayResultOrder;
import com.xyy.saas.payment.dao.model.RefundOrder;
import com.xyy.saas.payment.merchant.core.dto.RechargeHandleDto;
import com.xyy.saas.payment.service.OrderService;
import com.xyy.saas.payment.service.PayResultOrderService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author wangzeqi
 */
@Service
@RequiredArgsConstructor
public class RechargeFallBackService {

    private final CallbackRunner callbackRunner;
    private final PayResultOrderService payResultOrderService;
    private final OrderService orderService;

    public void handlePayRecharge(LocalDateTime beginTime, LocalDateTime endTime) {
        List<PayResultOrder> payResultOrderList = payResultOrderService.queryNoneRoyaltyList(beginTime, endTime);
        if (CollectionUtils.isEmpty(payResultOrderList)) {
            return;
        }

        for (PayResultOrder payResultOrder : payResultOrderList) {
            RechargeHandleDto rechargeHandleDto = RechargeHandleDto.builder().
                    rechargeType(RechargeHandleDto.PAY).
                    channel(payResultOrder.getPayChannel()).
                    orderNo(payResultOrder.getPayNo()).
                    accountId(payResultOrder.getReceiveId()).
                    build();
            callbackRunner.syncSendMsg(RocketMqTopic.TOPIC_RECHARGE_HANDLE, rechargeHandleDto);
        }
    }

    public void handleRefundRecharge(LocalDateTime beginTime, LocalDateTime endTime) {
        List<RefundOrder> refundOrderList = orderService.selectNoneRoyaltyRefundOrders(beginTime, endTime);
        if (CollectionUtils.isEmpty(refundOrderList)) {
            return;
        }

        for (RefundOrder refundOrder : refundOrderList) {
            RechargeHandleDto rechargeHandleDto = RechargeHandleDto.builder().
                    rechargeType(RechargeHandleDto.REFUND).
                    channel(refundOrder.getChannel()).
                    orderNo(refundOrder.getRefundNo()).
                    accountId(refundOrder.getUserId()).
                    build();
            callbackRunner.syncSendMsg(RocketMqTopic.TOPIC_RECHARGE_HANDLE, rechargeHandleDto);
        }
    }

}
